<?php
namespace Home\Controller;
use Think\Controller;
class ProjectController extends BaseController {
	public function __construct(){
		parent::__construct();
        $this->login_user = $this->checkLogin(false);
        if(!$this->login_user){
            $this->redirect('Home/Passport/login');
        }

        $this->project_id = I('pid');
        if($this->project_id){
            $type = M('Project')->where(['project_id'=>$this->project_id])->field('project_type')->find();
            if(!$type){
                $this->message('项目不存在！',U('Home/Index/index'));exit();
            }
            if($this->login_user['username'] == 'admin'){
                $this->self_auth = 'admin';
            }
            else{
                $this->self_auth = M('ProjectUser')->where(['project_id'=>$this->project_id,'user_id'=>$this->login_user['user_id']])->field('auth')->find()['auth'];
                if($type['project_type'] != 'public' && !$this->self_auth){
                    $this->message('抱歉，您没有查看该项目的权限',U('Home/Index/index'));exit();
                }
                elseif($type['project_type'] == 'public' && !$this->self_auth){
                    $this->self_auth = 'tour';
                }
            }
        }
        else{
            $this->redirect('Home/Index/index');
        }
	}

    public function index(){
        $Project = D('project');

        //项目信息
        $data = $Project->where("project_id = %d",[$this->project_id])->find();
        $user = M('User')->where(['user_id'=>$data['creator_id']])->field('username,nickname')->find();
        $data['creator'] = $user['nickname']?$user['nickname']:$user['username'];

        //统计
        $data['group_num'] = M('ProjectGroup')->where(['project_id'=>$this->project_id])->count();
        $data['api_num'] = M('Api')->where(['project_id'=>$this->project_id])->count();
        $data['member_num'] = M('ProjectUser')->where(['project_id'=>$this->project_id])->count();

        $page['bread'] = $data['project_name'];
        $page['project'] = $data;
        $page['active_menu'] = 'index';
        $this->assign($page);
        $this->display();
    }

    /**
     * ps ：添加项目分组
     * Time：2016/10/14 15:41:22
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function addGroup(){
        if($this->self_auth == 'tour'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!IS_POST){
            $this->assign('active_menu',['one'=>'group','two'=>'add']);
            $this->assign('bread','创建分组');
            $this->display();
        }
        else{
            $Group = D('ProjectGroup');
            if($Group->create()){
                $result =  $Group->add();
                if($result) {
                    $this->ajaxReturn(['success'=>true,'msg'=>'分组创建成功！','url'=>U('Home/Project/groupList',['pid'=>$this->project_id])]);exit;
                }else{
                    $this->ajaxReturn(['success'=>false,'msg'=>'分组创建失败！']);exit;
                }
            }
            else{
                $this->ajaxReturn($Group->getError());
            }
        }
    }

    /**
     * ps ：编辑项目分组
     * Time：2016/10/14 15:41:22
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function editGroup(){
        if($this->self_auth == 'tour'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!IS_POST){
            $Group = D('ProjectGroup');
            $data = $Group->where("project_id = %d and group_id = %d",[$this->project_id,I('group_id')])->find();

            $this->assign($data);
            $this->assign('active_menu',['one'=>'group','two'=>'glist']);
            $this->assign('bread','编辑分组');
            $this->display();
        }
        else{
            $Group = D('ProjectGroup');
            if($Group->create()){
                $postdata = I('post.');
                $saveData = array(
                    'group_id' => $postdata['group_id'],
                    'group_name' => $postdata['group_name'],
                    'group_intro' => $postdata['group_intro'],
                );
                $result =  $Group->save($saveData);
                if($result !== false) {
                    $this->ajaxReturn(['success'=>true,'msg'=>'修改成功！','url'=>U('Home/Project/groupList',['pid'=>$this->project_id])]);exit;
                }else{
                    $this->ajaxReturn(['success'=>false,'msg'=>'修改失败！']);exit;
                }
            }
            else{
                $this->ajaxReturn(['success'=>false,'msg'=>$Group->getError()]);
            }
        }
    }

    /**
     * ps ：分组列表
     * Time：2016/10/14 16:22:46
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function groupList(){
        $Group = D('ProjectGroup');
        $filter = array(
            'project_id' => $this->project_id,
        );
        $data = $Group -> where($filter) -> select();

        $this->assign('active_menu',['one'=>'group','two'=>'glist']);
        $this->assign('bread','分组列表');
        $this->assign('groups',$data);
        $this->display();
    }

    /**
     * ps ：删除分组
     * Time：2016/10/17 09:28:28
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function removeGroup(){
        if($this->self_auth == 'tour'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!IS_POST){
            $this->redirect('Home/Project/groupList');
        }
        else{
            $group_id = I('group_id');
            $Group = D('ProjectGroup');
            if($Group->where(['group_id'=>$group_id,'project_id'=>$this->project_id])->delete()){
                $this->ajaxReturn(['success'=>true,'msg'=>'删除成功！','url'=>U('Home/Project/groupList',['pid'=>$this->project_id])]);exit;
            }
            else{
                $this->ajaxReturn(['success'=>false,'msg'=>'删除失败！']);
            }
        }
    }

    /**
     * ps ：添加API接口
     * Time：2016/10/17 09:31:04
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function addApi(){
        if($this->self_auth == 'tour'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!IS_POST){
            $Group = D('ProjectGroup');
            $filter = array(
                'project_id' => $this->project_id,
            );
            $data = $Group -> where($filter) -> select();

            //获取api信息
            if(I('aid')){
                $apiInfo = D('Api') -> where(['api_id'=>I('aid')]) -> find();
                $apiInfo['param'] = unserialize($apiInfo['param']);
                $apiInfo['ret_param'] = unserialize($apiInfo['return_param']);
                $this->assign('api_info',$apiInfo);
            }

            $this->assign('active_menu',['one'=>'api','two'=>'add']);
            $this->assign('bread','创建接口');
            $this->assign('groups',$data);
            $this->display();
        }
        else{
            $Api = D('Api');
            $postdata = I('post.');
            // $Api -> startTrans();

            if($Api -> create()){
                $saveData = array(
                    'project_id' => $this->project_id,
                    'api_name' => $postdata['api_name'],
                    'api_intro' => $postdata['api_intro'],
                    'group_id' => $postdata['group_id'],
                    'request_url' => $postdata['request_url'],
                    'api_method' => $postdata['api_method'],
                    'create_time' => time(),
                    'creator_id' => $this->login_user['user_id'],
                    'return_example' => $postdata['return_example'],
                    'error_example' => $postdata['error_example'],
                    'memo' => $postdata['memo'],
                );
                //接口参数
                foreach ($postdata['param_name'] as $k => $v) {
                    // $apiParam[$k]['api_id'] = $api_id;
                    // $apiParam[$k]['project_id'] = $this->project_id;
                    $apiParam[$k]['param_name'] = $v;
                    $apiParam[$k]['param_intro'] = $postdata['param_intro'][$k];
                    $apiParam[$k]['param_type'] = $postdata['param_type'][$k];
                    $apiParam[$k]['param_must'] = $postdata['param_must'][$k];
                    $apiParam[$k]['param_default'] = $postdata['param_default'][$k];
                    // if(!M('ApiParam')->add($apiParam)){
                    //     $Api->rollback();
                    //     $this->ajaxReturn(['success'=>false,'msg'=>'添加失败']);exit();
                    // }
                }
                $saveData['param'] = serialize($apiParam);
                //接口返回参数
                foreach ($postdata['ret_param_name'] as $k => $v) {
                    $retParam[$k]['ret_param_name'] = $v;
                    $retParam[$k]['ret_param_intro'] = $postdata['ret_param_intro'][$k];
                    $retParam[$k]['ret_param_type'] = $postdata['ret_param_type'][$k];
                }
                $saveData['return_param'] = serialize($retParam);
                if($api_id = $Api -> add($saveData)){
                    // $Api->commit();
                    $this->ajaxReturn(['success'=>true,'msg'=>'添加成功','url'=>U('Home/Project/apiList',['pid'=>$this->project_id])]);
                }
                else{
                    // $Api->rollback();
                    $this->ajaxReturn(['success'=>false,'msg'=>'添加失败']);
                }
            }
            else{
                // $Api->rollback();
                $this->ajaxReturn(['success'=>false,'msg'=>$Api->getError()]);
            }
        }
    }

    /**
     * ps ：api列表
     * Time：2016/10/17 14:19:42
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function apiList(){
        //获取分组信息
        $Api = D('Api');
        $Group = D('ProjectGroup');
        $filter = array(
            'project_id' => $this->project_id,
        );
        $data = $Group -> where($filter) -> select();
        foreach ($data as &$group) {
            $group['count'] = $Api->where(['group_id'=>$group['group_id']])->count();
        }

        //获取接口列表
        $apiFilter = array(
            'project_id' => $this->project_id,
        );
        $page_no = I('page_no')?I('page_no'):1;
        $pagesize = 20;
        if(I('gid')){
            $apiFilter['group_id'] = I('gid');
        }
        if(I('search_keyword')){
            $apiFilter['_complex']['api_name'] = array('like','%'.I('search_keyword').'%');
            $apiFilter['_complex']['api_intro'] = array('like','%'.I('search_keyword').'%');
            $apiFilter['_complex']['_logic'] = 'or';
        }
        $apiFilter['_logic'] = 'and';
        $apiList = $Api -> where($apiFilter) -> page($page_no,$pagesize) -> select();
        $api_count = $Api-> where(['project_id'=>$this->project_id]) -> count();
        $count = $Api->where($apiFilter)->count();
        $page['count'] = ceil($count/$pagesize);
        $page['current'] = $page_no;
        $apiFilter['search_keyword'] = I('search_keyword');

        C('TOKEN_ON',false);
        $this->assign('active_menu',['one'=>'api','two'=>'apilist']);
        $this->assign('bread','接口列表');
        $this->assign('groups',$data);
        $this->assign('apis',$apiList);
        $this->assign('active_filter',$apiFilter);
        $this->assign('page',$page);
        $this->assign('api_count',$api_count);
        $this->display();
    }

    /**
     * ps ：编辑api接口
     * Time：2016/10/18 09:51:20
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function editApi(){
        if($this->self_auth == 'tour'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!IS_POST){
            $Group = D('ProjectGroup');
            $filter = array(
                'project_id' => $this->project_id,
            );
            $data = $Group -> where($filter) -> select();

            //获取api信息
            if(I('aid')){
                $filter['api_id'] = I('aid');
                $apiInfo = D('Api') -> where($filter) -> find();
                $apiInfo['param'] = unserialize($apiInfo['param']);
                $apiInfo['ret_param'] = unserialize($apiInfo['return_param']);
                $this->assign('api_info',$apiInfo);
            }

            $this->assign('active_menu',['one'=>'api','two'=>'apilist']);
            $this->assign('bread','创建接口');
            $this->assign('groups',$data);
            $this->display();
        }
        else{
            $Api = D('Api');
            $postdata = I('post.');
            // $Api -> startTrans();
            if(!$postdata['aid']){
                $this->ajaxReturn(['success'=>false,'msg'=>'修改失败！','url'=>U('Home/Project/apiList',['pid'=>$this->project_id])]);
            }

            if($Api -> create()){
                $saveData = array(
                    'api_id' => $postdata['aid'],
                    'project_id' => $this->project_id,
                    'api_name' => $postdata['api_name'],
                    'api_intro' => $postdata['api_intro'],
                    'group_id' => $postdata['group_id'],
                    'request_url' => $postdata['request_url'],
                    'api_method' => $postdata['api_method'],
                    'create_time' => time(),
                    'creator_id' => $this->login_user['user_id'],
                    'return_example' => $postdata['return_example'],
                    'error_example' => $postdata['error_example'],
                    'memo' => $postdata['memo'],
                );
                //接口参数
                foreach ($postdata['param_name'] as $k => $v) {
                    // $apiParam[$k]['api_id'] = $api_id;
                    // $apiParam[$k]['project_id'] = $this->project_id;
                    $apiParam[$k]['param_name'] = $v;
                    $apiParam[$k]['param_intro'] = $postdata['param_intro'][$k];
                    $apiParam[$k]['param_type'] = $postdata['param_type'][$k];
                    $apiParam[$k]['param_must'] = $postdata['param_must'][$k];
                    $apiParam[$k]['param_default'] = $postdata['param_default'][$k];
                    // if(!M('ApiParam')->add($apiParam)){
                    //     $Api->rollback();
                    //     $this->ajaxReturn(['success'=>false,'msg'=>'添加失败']);exit();
                    // }
                }
                $saveData['param'] = serialize($apiParam);
                //接口返回参数
                foreach ($postdata['ret_param_name'] as $k => $v) {
                    $retParam[$k]['ret_param_name'] = $v;
                    $retParam[$k]['ret_param_intro'] = $postdata['ret_param_intro'][$k];
                    $retParam[$k]['ret_param_type'] = $postdata['ret_param_type'][$k];
                }
                $saveData['return_param'] = serialize($retParam);
                if($api_id = $Api -> save($saveData)){
                    // $Api->commit();
                    $this->ajaxReturn(['success'=>true,'msg'=>'修改成功','url'=>U('Home/Project/apiList',['pid'=>$this->project_id])]);
                }
                else{
                    // $Api->rollback();
                    $this->ajaxReturn(['success'=>false,'msg'=>'修改失败']);
                }
            }
            else{
                // $Api->rollback();
                $this->ajaxReturn(['success'=>false,'msg'=>$Api->getError()]);
            }
        }
    }

    /**
     * ps ：删除Api
     * Time：2016/10/18 10:23:30
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function deleteApi(){
        if($this->self_auth == 'tour'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!I('aid')){
            $this->ajaxReturn(['success'=>false,'msg'=>'删除失败！']);
        }
        $filter = array(
            'project_id' => $this->project_id,
            'api_id' => I('aid'),
        );
        $result = D('Api')->where($filter)->delete();
        if($result){
            $this->ajaxReturn(['success'=>true,'msg'=>'删除成功！','url'=>U('Home/Project/apiList',['pid'=>$this->project_id])]);
        }
        else{
            $this->ajaxReturn(['success'=>false,'msg'=>'删除失败！']);
        }
    }

    /**
     * ps ：api详情页
     * Time：2016/10/18 13:10:20
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function apiDetail(){
        $filter = array(
            'project_id' => $this->project_id,
        );

        //获取api信息
        if(I('aid')){
            $filter['api_id'] = I('aid');
            $apiInfo = D('Api') -> where($filter) -> find();
            $apiInfo['param'] = unserialize($apiInfo['param']);
            $apiInfo['ret_param'] = unserialize($apiInfo['return_param']);
            $this->assign('api_info',$apiInfo);
        }
        else{
            $this->redirect('Home/Project/apiList',['pid'=>$this->project_id]);
        }

        $this->assign('active_menu',['one'=>'api','two'=>'apilist']);
        $this->assign('bread','接口详情');
        $this->assign('apibtn',1);
        $this->display();
    }

    /**
     * ps ：接口测试
     * Time：2016/10/18 14:05:42
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function testApi(){
        if(!IS_POST){
            $filter = array(
                'project_id' => $this->project_id,
            );

            //获取api信息
            if(I('aid')){
                $filter['api_id'] = I('aid');
                $apiInfo = D('Api') -> where($filter) -> find();
                $apiInfo['param'] = unserialize($apiInfo['param']);
                $apiInfo['ret_param'] = unserialize($apiInfo['return_param']);
                $this->assign('api_info',$apiInfo);
            }
            else{
                $this->redirect('Home/Project/apiList',['pid'=>$this->project_id]);
            }
            $sign_path = M('ProjectSign')->where(['project_id'=>$this->project_id])->field('sign_path')->find()['sign_path'];
            if($sign_path && file_exists($sign_path)){
                $this->assign('usesign_checked',1);
            }

            C('TOKEN_ON',false);
            $this->assign('active_menu',['one'=>'api','two'=>'apilist']);
            $this->assign('bread','接口测试');
            $this->display();
        }
        else{
            $postdata = I('post.');
            // dump($postdata);
            // dump($_FILES);die;
            $url = $postdata['request_url'];
            $method = strtolower($postdata['api_method']);
            // unset($postdata['pid'],$postdata['request_url'],$postdata['api_method']);

            try{
                foreach ($postdata['req'] as $k => $v) {
                    switch ($v['type']) {
                        case 'array':
                            break;
                        case 'file':
                            if(!strstr($k,'.')){
                                $files[$k]['name'] = $_FILES[$k]['name'];
                                $files[$k]['type'] = $_FILES[$k]['type'];
                                $files[$k]['tmp_name'] = $_FILES[$k]['tmp_name'];
                                $files[$k]['error'] = $_FILES[$k]['error'];
                                $files[$k]['size'] = $_FILES[$k]['size'];
                            }
                            else{
                                $keys = explode('.', $k);
                                $arr_key = '';
                                foreach ($keys as $kk => $vv) {
                                    if($kk == 0){
                                        $arr_key .= $vv;
                                    }
                                    else{
                                        $arr_key .= '['.$vv.']';
                                    }
                                }
                                $file_key = str_replace('.', '_', $k);
                                $files[$arr_key]['name'] = $_FILES[$file_key]['name'];
                                $files[$arr_key]['type'] = $_FILES[$file_key]['type'];
                                $files[$arr_key]['tmp_name'] = $_FILES[$file_key]['tmp_name'];
                                $files[$arr_key]['error'] = $_FILES[$file_key]['error'];
                                $files[$arr_key]['size'] = $_FILES[$file_key]['size'];
                            }
                            break;
                        default:
                            //转换类型暂时去掉，防止空值报错
                            // if(!empty($v['value'])){
                            //     settype($v['value'],$v['type']);
                            // }
                            if(!strstr($k,'.')){
                                $data[$k] = html_entity_decode($v['value']);
                            }
                            else{
                                $keys = explode('.', $k);
                                $arr_key = '';
                                foreach ($keys as $kk => $vv) {
                                    if($kk == 0){
                                        $arr_key .= $vv;
                                    }
                                    else{
                                        $arr_key .= '['.$vv.']';
                                    }
                                }
                                $data[$arr_key] = html_entity_decode($v['value']);
                            }
                            break;
                    }
                }
            }
            catch(Exception $e){
                $this->__set('result',$e->getMessage());
                echo $this->fetch('apiResult');
            }
            // dump($data);die;
            // dump($files);die;
            // dump($res);die;
            if($postdata['use_sign']){
                $sign_path = M('ProjectSign')->where(['project_id'=>$this->project_id])->field('sign_path')->find()['sign_path'];
                if($sign_path && file_exists($sign_path)){
                    require_once($sign_path);
                    $signData = $this->_make_arr($postdata);
                    if(isset($signData['sign'])){
                        unset($signData['sign']);
                    }
                    $data['sign'] = sign($signData);
                }
            }

            $httpclient = new \Home\Common\Util\HttpClient;
            if(!$files){
                if($method == 'get'){
                    $res = $httpclient->$method($url,$data);
                }
                else{
                    $res = $httpclient->upload($url,[],$data);
                }
            }
            else{
                $upload = new \Think\Upload();// 实例化上传类
                $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
                // 上传文件 
                $info   =   $upload->upload($files);
                foreach ($info as $key => $value) {
                    $postfiles[$key] = $upload->rootPath.$value['savepath'].$value['savename'];
                }
                $res = $httpclient->upload($url,$postfiles,$data);
            }
            $this->__set('result',$res);
            echo $this->fetch('apiResult');
        }
    }

    /**
     * ps ：形成签名用的数组
     * Time：2016/10/24 16:29:53
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    private function _make_arr($data){
        foreach ($data['req'] as $k => $v) {
            switch ($v['type']) {
                case 'array':
                    break;
                case 'file':
                    break;
                default:
                    if(!strstr($k,'.')){
                        $ret[$k] = html_entity_decode($v['value']);
                    }
                    else{
                        $keys = explode('.', $k);
                        $this->_arr_value($ret,$keys,$v['value'],1);
                    }
                    break;
            }
        }
        return $ret;
    }

    /**
     * ps ：多维数组赋值
     * Time：2016/10/24 16:30:05
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    private function _arr_value(&$arr,$keys,$value,$floor){
        if($floor == count($keys)){
            $key = $keys[$floor-1];
            $arr[$key] = html_entity_decode($value);
        }
        else{
            $key = $keys[$floor-1];
            $floor++;
            $this->_arr_value($arr[$key],$keys,$value,$floor);
        }
    }

    /**
     * ps ：用户管理
     * Time：2016/10/20 16:48:17
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function memberManage(){
        if($this->self_auth == 'tour' || $this->self_auth == 'dev'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        // $creator = M('Project')->where(['project_id'=>$this->project_id])->field('creator_id')->find();
        $members = M('ProjectUser')->where(['project_id'=>$this->project_id])->field('user_id,auth')->select();
        // $members[] = array(
        //     'user_id' => $creator['creator_id'],
        //     'auth' => 'owner',
        // );

        $User = M('User');
        foreach ($members as $k => &$v) {
            $tmp = $User->where(['user_id'=>$v['user_id']])->field('username,headurl')->find();
            $v['username'] = $tmp['username'];
            $v['headurl'] = $tmp['headurl'];
        }

        C('TOKEN_ON',false);
        $this->assign('active_menu',['one'=>'project','two'=>'memberManage']);
        $this->assign('bread','成员管理');
        $this->assign('members',$members);
        $this->display();
    }

    public function addMember(){
        if($this->self_auth == 'tour' || $this->self_auth == 'dev'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        $postdata = I('post.');
        $projectUser = M('ProjectUser');

        $data['user_id'] = $postdata['user_id'];
        $data['project_id'] = $this->project_id;
        if(!$postdata['user_id']){
            $this->ajaxReturn(['success'=>false,'msg'=>'请选择一个用户']);
        }

        if($projectUser->where($data)->count() > 0){
            $this->ajaxReturn(['success'=>false,'msg'=>'该用户已在项目中']);
        }
        else{
            $data['auth'] = $postdata['auth'];
            if(!$projectUser->add($data)){
                $this->ajaxReturn(['success'=>false,'msg'=>'添加失败！']);
            }
            else{
                $this->ajaxReturn(['success'=>true,'msg'=>'添加成功！','url'=>U('Home/Project/memberManage',['pid'=>$this->project_id])]);exit;
            }
        }
    }

    /**
     * ps ：移除成员
     * Time：2016/10/21 09:16:33
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function removeMember(){
        if($this->self_auth == 'tour' || $this->self_auth == 'dev'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!IS_POST){
            $this->redirect('Home/Project/memberManage',['pid'=>$this->project_id]);
        }
        $user_id = I('uid');
        if(M('ProjectUser')->where(['project_id'=>$this->project_id,'user_id'=>$user_id])->delete()){
            $this->ajaxReturn(['success'=>'true','msg'=>'操作成功','url'=>U('Home/Project/memberManage',['pid'=>$this->project_id])]);
        }
        else{
            $this->ajaxReturn(['success'=>false,'msg'=>'操作失败！']);
        }
    }

    /**
     * ps ：修改权限
     * Time：2016/10/21 09:31:49
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function editAuth(){
        if($this->self_auth == 'tour' || $this->self_auth == 'dev'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!IS_POST){
            $this->redirect('Home/Project/memberManage',['pid'=>$this->project_id]);
        }
        $user_id = I('uid');
        $auth = I('edit_auth');
        if(M('ProjectUser')->where(['project_id'=>$this->project_id,'user_id'=>$user_id])->save(['auth'=>$auth])){
            $this->ajaxReturn(['success'=>'true','msg'=>'操作成功','url'=>U('Home/Project/memberManage',['pid'=>$this->project_id])]);
        }
        else{
            $this->ajaxReturn(['success'=>false,'msg'=>'操作失败！']);
        }
    }

    /**
     * ps ：移交项目
     * Time：2016/10/21 10:02:24
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function handProject(){
        if($this->self_auth == 'tour' || $this->self_auth == 'dev'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!IS_POST){
            $this->redirect('Home/Project/memberManage',['pid'=>$this->project_id]);
        }
        $user_id = I('uid');
        $auth = I('edit_auth');
        $projectUser = M('ProjectUser');
        $projectUser->startTrans();
        $first = $projectUser->where(['project_id'=>$this->project_id,'user_id'=>$user_id])->save(['auth'=>'owner']);
        $second = $projectUser->where(['project_id'=>$this->project_id,'user_id'=>$this->login_user['user_id']])->save(['auth'=>'admin']);
        if($first && $second){
            $projectUser->commit();
            $this->ajaxReturn(['success'=>'true','msg'=>'操作成功','url'=>U('Home/Project/memberManage',['pid'=>$this->project_id])]);
        }
        else{
            $projectUser->rollback();
            $this->ajaxReturn(['success'=>false,'msg'=>'操作失败！']);
        }
    }

    /**
     * ps ：项目信息编辑
     * Time：2016/10/21 11:05:32
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function projectInfo(){
        if($this->self_auth == 'tour' || $this->self_auth == 'dev'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        if(!IS_POST){
            $projectInfo = M('Project')->where(['project_id'=>$this->project_id])->find();
            C('TOKEN_ON',false);
            $this->assign('active_menu',['one'=>'project','two'=>'projectInfo']);
            $this->assign('bread','项目信息');
            $this->assign('project',$projectInfo);
            $this->display();
        }
        else{
            $postdata = I('post.');
            $data = array(
                'project_id' => $this->project_id,
                'project_name' => $postdata['project_name'],
                'project_intro' => $postdata['project_intro'],
                'project_type' => $postdata['project_type'],
            );
            $Project = D('Project');
            $result =   $Project->save($data);
            // if($result) {
            $this->ajaxReturn(['success'=>true,'msg'=>'修改成功！','url'=>U('Home/Project/projectInfo',['pid'=>$this->project_id])]);exit;
            // }else{
            //     $this->ajaxReturn(['success'=>false,'msg'=>'修改失败！']);exit;
            // }
        }
    }

    /**
     * ps ：项目管理
     * Time：2016/10/21 12:41:16
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function projectManage(){
        if($this->self_auth == 'tour' || $this->self_auth == 'dev'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }
        $this->assign('active_menu',['one'=>'project','two'=>'projectManage']);
        $this->assign('bread','项目管理');
        $this->assign('project',$projectInfo);
        $this->display();
    }

    public function deleteProject(){
        if($this->self_auth == 'tour' || $this->self_auth == 'dev'){
            $this->ajaxReturn(['success'=>false,'msg'=>'抱歉，您没有权限','url'=>U('Home/Project/index',['pid'=>$this->project_id])]);exit;
        }
        $Project = M('Project');
        $Project -> startTrans();

        $filter = ['project_id'=>$this->project_id];
        //第一步，删除用户信息
        $proUser = M('ProjectUser')->where($filter)->delete();
        //第二步，删除api接口
        $api = M('Api')->where($filter)->delete();
        //第三步，删除分组信息
        $group = M('ProjectGroup')->where($filter)->delete();
        //第四步，删除项目信息
        $pro = $Project->where($filter)->delete();;

        if($proUser !== false && $api !== false && $group !== false && $pro !== false){
            $Project->commit();
            $this->ajaxReturn(['success'=>true,'msg'=>'操作成功！','url'=>U('Home/Index/index')]);exit;
        }
        else{
            $Project->rollback();
            $this->ajaxReturn(['success'=>false,'msg'=>'操作失败！']);exit;
        }
    }

    /**
     * ps ：签名算法管理
     * Time：2016/10/24 09:05:59
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function signManage(){
        if($this->self_auth == 'tour' || $this->self_auth == 'dev'){
            $this->message('抱歉，您没有权限',U('Home/Project/index',['pid'=>$this->project_id]));exit();
        }
        if(!IS_POST){
            $signDemo = '<?php
    function sign($params){
        /*code...*/
        return $sign;
    }
?>';
            $file_path = M('ProjectSign')->where(['project_id'=>$this->project_id])->field('sign_path')->find()['sign_path'];
            //判断文件是否存在 
            if(file_exists($file_path)){ 
                //判断文件是否能打开 
                if($fp=fopen($file_path,"r")){ 
                    $str=""; 
                    for($i=1;! feof($fp);$i++){
                        $str .= '<div class="line"><span class="line-tag">'.$i.'.</span><span class="line-content">'.htmlentities(fgets($fp)). '</div>'; 
                    } 
                }else{ 
                    $str .= "文件不能打开"; 
                } 
            }else{ 
                $str .= "没有这个文件"; 
            } 
            //替换字符 
            // $str=str_replace("\r","",$str); 
            fclose($fp);

            $this->assign('active_menu',['one'=>'api','two'=>'sign']);
            $this->assign('bread','签名管理');
            $this->assign('signDemo',$signDemo);
            $this->assign('signContent',$str);
            $this->display();
        }
        else{
            $upload = new \Think\Upload();// 实例化上传类
            $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
            $upload->exts      =     array('txt', 'php');// 设置附件上传类型
            // 上传文件 
            $info   =   $upload->upload($_FILES)['signFile'];

            $data = array(
                'project_id' => $this->project_id,
                'sign_path' => $upload->rootPath.$info['savepath'].$info['savename'],
                'status' => 'progress',
                'creator_id' => $this->login_user['user_id'],
                'create_memo' => I('create_memo'),
                'create_time' => time(),
            );
            if(M('ProjectSignApply')->add($data)){
                $this->message('提交成功！请耐心等待管理员审核',U('Home/Project/signManage',['pid'=>$this->project_id]));exit;
            }
            else{
                $this->message('操作失败！',U('Home/Project/signManage',['pid'=>$this->project_id]));exit;
            }
        }
    }

    public function exportTxt(){
        $filter = array(
            'project_id' => $this->project_id,
        );
        if(I('gid')){
            $filter['group_id'] = I('gid');
        }
        $apiList = D('Api')->where($filter)->field('api_intro,request_url,param,return_example')->select();
        if(!$apiList){
            $this->message('没有找到相关数据！',U('Home/Project/apiList',['pid'=>$this->project_id]));exit;
        }

        //写入文件
        $filename = TEMP_PATH.'export_'.date('ymdHis').'.txt';
        $import_data = '';
        foreach ($apiList as $k => $v) {
            $import_data .= '[remark]'.$v['api_intro']."\r\n";
            $import_data .= '[url]'.$v['request_url']."\r\n";
            $params = unserialize($v['param']);
            // $param = [];
            // foreach ($params as $value) {
            //     $param[$value['param_name']] = $value['param_default'];
            // }
            // $import_data .= '[param]params='.json_encode($param)."\r\n";
            $param = '';
            foreach ($params as $value) {
                if($param !== ''){
                    $param .= '&';
                }
                $param .= $value['param_name'].'='.$value['param_default'];
            }
            $import_data .= '[param]'.$param."\r\n";
            $import_data .= '[response]'.html_entity_decode($v['return_example'])."\r\n";
        }
        $handle = fopen($filename, 'a');
        if(!$handle) {
            echo "文件打开失败,请检查权限";exit;
        }
        if(!flock($handle, LOCK_EX)) {
            echo "系统必须支持文件锁flock";
            exit;
        }

        fwrite($handle, (string) $import_data);
        flock($handle, LOCK_UN);
        fclose($handle);

        if(file_exists($filename)){
            //打开文件
            $file = fopen($filename, "r");
            //返回的文件类型
            Header("Content-type: application/octet-stream");
            //按照字节大小返回
            Header("Accept-Ranges: bytes");
            //返回文件的大小
            Header("Accept-Length: " . filesize($filename));
            //这里对客户端的弹出对话框，对应的文件名
            Header("Content-Disposition: attachment; filename=apitxt.txt");
            //一次只传输1024个字节的数据给客户端
            //向客户端回送数据
            $buffer = 1024; //
            //判断文件是否读完
            while (!feof($file)) {
                //将文件读入内存
                $file_data = fread($file, $buffer);
                //每次向客户端回送1024个字节的数据
                echo $file_data;
            }
             
            fclose($file);
            unlink($filename); //删除文件
        }
    }
}